#include "math.h"

#include "SignalCaracterizerModule.h"
#include "DigitalManagerModule.h"

#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"

#include "LED2.h"              
#include "utilidades.h"


extern xSemaphoreHandle xSemaphore;
extern xTaskHandle xHandleTimeOut;

xSemaphoreHandle xNewMeasureDurationSemaphore;

/* documentar */
static uint16_t uiCntSamples = 0;
static uint16_t CntSamples = 0;
static uint16_t iCntSamples_temp = 0;


void vTaskTimeOut( void * pvParameters )
{
  const portTickType xDelay = 100 / portTICK_RATE_MS;
  pvParameters = pvParameters;
  for(;;)
  {
    vTaskSuspend(xHandleTimeOut);
    vTaskDelay( xDelay );
    //HexToScreen(&uiCntSamples);
    xSemaphoreGive( xNewMeasureDurationSemaphore );
    CntSamples = uiCntSamples;
    uiCntSamples = 0;
  }
}

void vTaskCode2( void * pvParameters )
{
 const portTickType xDelay = 1 / portTICK_RATE_MS;   
 pvParameters = pvParameters;
 int16_t iSxME = 0;
 uint16_t iSampleSxME_n_1 = 0;
 bool bEventRissing = FALSE;

 
 vSemaphoreCreateBinary( xNewMeasureDurationSemaphore ); 
 
     for( ;; )
     {
        xSemaphoreTake( xSemaphore, portMAX_DELAY );
        DMM_GetSampleSxME(&iSxME);
        xSemaphoreGive( xSemaphore );
        iSxME = (int16_t)abs(iSxME);
        if(iSxME > 1500)//2000
        {
          // disparar un timeout de 500 ms y ckequear el valor de contador
          if( xTaskIsTaskSuspended(xHandleTimeOut) )
          {
              vTaskResume(xHandleTimeOut);
          }
          LED2_NegVal();
          ++uiCntSamples;
        }
        vTaskDelay( xDelay );
     }
 }
  
  
bool GetDuration( uint16_t * piuCntSamples, int16_t * piSampleFrecuency )
{
     *piuCntSamples = CntSamples;
     *piSampleFrecuency = 1;
}

/* 
if(uiSampleSxME >= 32767 && uiSampleSxME_n_1 < uiSampleSxME && !bEventRissing)
        {
          bEventRissing = TRUE;
        }
       
        if(uiSampleSxME < 32767 && uiSampleSxME_n_1 > uiSampleSxME && bEventRissing ) 
        {
          bEventRissing = FALSE; 
          uiCntSamples = iCntSamples_temp;          
          xSemaphoreGive( xNewMeasureDurationSemaphore );       
        }
       
        if( bEventRissing == TRUE )      
        {
          
          ++iCntSamples_temp;
        }
        else
        {
          iCntSamples_temp = 0;        
        }
       
        uiSampleSxME_n_1 = uiSampleSxME;
*/